package org.rcy.ruicingmarket.controller;

import com.egzosn.pay.ali.api.AliPayConfigStorage;
import com.egzosn.pay.ali.api.AliPayService;
import com.egzosn.pay.ali.bean.AliTransactionType;
import com.egzosn.pay.common.api.PayService;
import com.egzosn.pay.common.bean.MethodType;
import com.egzosn.pay.common.bean.PayOrder;
import com.egzosn.pay.common.http.HttpConfigStorage;
import org.rcy.ruicingmarket.handler.AliPayMessageHandler;
import org.rcy.ruicingmarket.interceptor.AliPayMessageInterceptor;
import org.rcy.ruicingmarket.order.OrderClient;
import org.rcy.ruicingmarket.order.OrderShowResponse;
import org.rcy.ruicingmarket.paytype.PayType;
import org.rcy.ruicingmarket.request.AliPaymentInitRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.imageio.ImageIO;
import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.util.Map;

/**
 * @author 吴康桥
 * @Description
 * @date 2022/11/7 14:47
 */

@RestController
@RequestMapping("/alipay")
public class AliPayController {

	private PayService payService;

	private HttpConfigStorage httpConfigStorage;
	@Autowired
	private AliPayMessageHandler aliPayMessageHandler;
	@Autowired
	private AliPayMessageInterceptor aliPayMessageInterceptor;
	@Autowired
	private OrderClient orderClient;

	@PostConstruct
	public void inti(){
		//请求连接池配置
		httpConfigStorage = new HttpConfigStorage();
		//最大连接数
		httpConfigStorage.setMaxTotal(20);
		//默认的每个路由的最大连接数
		httpConfigStorage.setDefaultMaxPerRoute(10);
	}

	@PostMapping("/initpage")
	public String initPayPage(@RequestBody AliPaymentInitRequest request){
		try {
			initAliPay(request);
			PayOrder order = buildPayOrder(request);
			if (order == null) {
				throw new RuntimeException("初始化参数异常");
			}
			//网页支付
			order.setTransactionType(AliTransactionType.PAGE);
			//获取支付订单信息
			Map orderInfo = payService.orderInfo(order);
			//组装成html表单信息
			return payService.buildRequest(orderInfo, MethodType.POST);

		} catch (Exception e) {
				return null;
		} finally {
			//释放支付服务
			payService = null;
		}
	}

	/**
	 * 获取二维码图像
	 * 二维码支付
	 * @return
	 */
	@RequestMapping(value = "toQrPay.jpg", produces = "image/jpeg;charset=UTF-8")
	public byte[] initQrPay(@RequestBody AliPaymentInitRequest request) {
		try {
			initAliPay(request);
			PayOrder order = buildPayOrder(request);
			if(order == null) {
				throw new RuntimeException("初始化参数异常");
			}
			//扫码付
			order.setTransactionType(AliTransactionType.SWEEPPAY);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ImageIO.write(payService.genQrPay(order), "JPEG", baos);
			return baos.toByteArray();
		}catch (Exception e){
		    return null;
		}
	}

	private void initAliPay(AliPaymentInitRequest request){
		payService = new AliPayService(buildPayConfigStorage(request),httpConfigStorage);
		payService.addPayMessageInterceptor(aliPayMessageInterceptor);
		payService.setPayMessageHandler(aliPayMessageHandler);
	}

	private AliPayConfigStorage buildPayConfigStorage(AliPaymentInitRequest request){
		AliPayConfigStorage aliPayConfigStorage = new AliPayConfigStorage();
		aliPayConfigStorage.setPayType(PayType.aliPay.name());
		aliPayConfigStorage.setAppid(request.getAppId());
		aliPayConfigStorage.setPid(request.getPid());
		aliPayConfigStorage.setSeller(request.getSeller());
		return aliPayConfigStorage;
	}

	private PayOrder buildPayOrder(AliPaymentInitRequest request){
		PayOrder payOrder = new PayOrder();
		ResultMessage<OrderShowResponse> response = orderClient.getByOrderId(Long.parseLong(request.getOutTradeNo()));
		if(!response.isFlag()){
			return null;
		}
		OrderShowResponse data = response.getData();
		payOrder.setPrice(new BigDecimal(data.getPayPrice()/100));
		payOrder.setOutTradeNo(request.getOutTradeNo());
		payOrder.setSubject(data.getTitle());
		payOrder.setBody(data.getResume());
		return payOrder;
	}
}
